//
//  MTLuckyReportViewController.swift
//  MT
//
//  Created by ooops on 2020/1/22.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTLuckyReportViewController: BaseViewController {
    
    private lazy var luckyProvider: MTProvider<MTLuckyAPI> = {
        let provider = MTProvider<MTLuckyAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private var result: [MTLuckyReportSubModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTLuckyReportCell.self, forCellReuseIdentifier: MTLuckyReportCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.backgroundColor = UIColor.white
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
    
    override func refreshView() {
        loadFirst()
    }
    
    
    // MARK: - 加载数据
    /// - Parameter loadMore: 是否加载更多
    private func loadData(loadMore: Bool) {
        let queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : pageSize]
        
        luckyProvider.rx.requestResult(.report).subscribe(onNext: { [weak self] (result:Result<MTLuckyReportModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 200 {
                    weakSelf.tableView.mj_footer?.endRefreshing()
                    weakSelf.tableView.mj_header?.endRefreshing()
                    if weakSelf.currentPage == 1 {
                        weakSelf.tableView.mj_footer?.state = .idle
                    }
                    
                    if let r = model.result {
                        if (model.page?.pages == weakSelf.currentPage) {
                            weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                        if loadMore == true {
                            weakSelf.result = weakSelf.result + r
                        } else {
                            weakSelf.result = r
                        }
                        
                        weakSelf.hiddenHF(isHidden: weakSelf.result.count == 0)
                    } else {
                        weakSelf.hiddenHF(isHidden: true)
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                }
                break
            case .failure(let error):
                
                break
            }
            
        }).disposed(by: globalDisposedBag)
        
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "抽奖记录"
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadFirst()
    }
}

extension MTLuckyReportViewController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTLuckyReportCell.reuseIdentity(), for: indexPath) as! MTLuckyReportCell
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTLuckyReportCell, forRowAt indexPath: IndexPath) {
        let model: MTLuckyReportSubModel = self.result[indexPath.row]
        cell.bind(model: model)
        
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTLuckyReportViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
